package cn.boltzjf.sql4j.ext.mysql;

import java.util.UUID;

import cn.boltzjf.sql4j.dao.ValueConverter;

public class MysqlTypeUtils {
    
    public static final ValueConverter VALUE_CONVERTER = new ValueConverter();

    public static byte[] uuidToBin(UUID uuid) {
        byte[] bytes = new byte[16];
        long m = uuid.getMostSignificantBits();
        long l = uuid.getLeastSignificantBits();
        for (int i = 0; i < 8; ++i) {
            bytes[i] = (byte) (m >> ((7 - i) << 3));
            bytes[i + 8] = (byte) (l >> ((7 - i) << 3));
        }
        return bytes;
    }
    
    public static UUID binToUuid(byte[] bytes) {
        if (bytes == null) {
            return null;
        }
        
        if (bytes.length != 16) {
            throw new IllegalArgumentException("Length of byte array should be 16");
        }
        
        long m = 0;
        long l = 0;
        for (int i = 0; i < 8; ++i) {
            m = (m << 8) | (255 & bytes[i]);
            l = (l << 8) | (255 & bytes[i + 8]);
        }
        
        return new UUID(m, l);
    }

}
